﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Halcon_chepai
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
            InitializeCamera();
        }

        //八嘎雅鹿
        HImage image;
        HRegion region=new HRegion();


        // 声明全局变量
        private HWindow _hWindow; //显示窗体的引用
        private HFramegrabber _framegrabber; //相机采集器
        private bool _isGrabbing = false; //是否继续采集
        private Thread _grabThread; //声明一个实时采集图像的线程

        private void label1_Click(object sender, EventArgs e)
        {

        }

        // 初始化相机
        private void InitializeCamera()
        {
            try
            {
                // 打开相机（参数需根据相机类型调整）
                _framegrabber = new HFramegrabber("GigEVision2", 0, 0, 0, 0, 0, 0, "default",
                                                  -1, "default", -1, "false", "default",
                                                  "default", 0, -1);

                // 获取 HSmartWindowControl 的 Halcon 窗口句柄
                _hWindow = hswcCar.HalconWindow;
            }
            catch (HalconException ex)
            {
                //MessageBox.Show($"相机初始化失败: {ex.Message}");
            }
        }

        // 采集循环（在独立线程中运行）
        private void GrabLoop()
        {
            while (_isGrabbing)
            {
                try
                {
                    // 抓取图像
                    image = _framegrabber.GrabImageAsync(-1);

                    // 在 Halcon 窗口中显示图像
                    _hWindow.DispObj(image);
                    HTuple width, height;
                    //获取图片的宽高
                    HOperatorSet.GetImageSize(image, out width, out height);
                    HOperatorSet.SetPart(hswcCar.HalconWindow, 0, 0, height - 1, width - 1);
                    this.hswcCar.HalconWindow.DispObj(image);
                    image.Dispose();
                }
                catch (HalconException ex)
                {
                    // 处理异常（如相机断开）
                    if (ex.GetErrorCode() == 5302) // 采集超时
                        Thread.Sleep(1000);
                    else
                        break;
                }
            }
        }

        // 开始实时采集
        private void StartGrabbing()
        {
            if (_framegrabber == null) InitializeCamera();

            _isGrabbing = true;
            //定义线程，在线程方法进行图像循环采集
            _grabThread = new Thread(GrabLoop);
            _grabThread.IsBackground = true;
            _grabThread.Start();
        }

        // 停止采集
        private void StopGrabbing()
        {
            _isGrabbing = false;
            _grabThread?.Join(); // 等待线程结束
            _framegrabber?.Dispose();
            _framegrabber = null;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            //OpenFileDialog ofd = new OpenFileDialog();
            //ofd.Filter = "所有图片|*.bmp;*.jpg";
            //ofd.Title = "加载图片";
            //ofd.RestoreDirectory = true;
            //if (ofd.ShowDialog() == DialogResult.OK)
            //{
            //   image = new HImage(ofd.FileName);
            //    HTuple width, height;
            //    //获取图片的宽高
            //    HOperatorSet.GetImageSize(image, out width, out height);
            //    HOperatorSet.SetPart(hswcCar.HalconWindow, 0, 0, height - 1, width - 1);
            //    this.hswcCar.HalconWindow.DispObj(image);
            //}

            //Halcon转的代码连续采集加载不出来
            //HObject ho_Image = null;
            //HTuple hv_AcqHandle = new HTuple();
            //HOperatorSet.GenEmptyObj(out ho_Image);
            //HOperatorSet.OpenFramegrabber("MediaFoundation", 0, 0, 0, 0, 0, 0, "progressive",
            //    -1, "default", -1, "false", "default", "Chicony_USB2.0_Camera_vid_04f2&pid_b729&mi_00#7&191d7230&1&0000",
            //    0, -1, out hv_AcqHandle);
            //HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
            //while ((int)(1) != 0)
            //{
            //    ho_Image.Dispose();
            //    HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);

            //    HTuple width, height;
            //    //获取图片的宽高
            //    HOperatorSet.GetImageSize(ho_Image, out width, out height);
            //    HOperatorSet.SetPart(hswcCar.HalconWindow, 0, 0, height - 1, width - 1);
            //    this.hswcCar.HalconWindow.DispObj(ho_Image);
            //}
            //HOperatorSet.CloseFramegrabber(hv_AcqHandle);
            //ho_Image.Dispose();
            //hv_AcqHandle.Dispose();


            StartGrabbing();

        }




        private void button2_Click(object sender, EventArgs e)
        {
            //region.TextLineOrientation(image, 50, (new HTuple(-50)).TupleRad(), (new HTuple(50)).TupleRad());
            HOperatorSet.TextLineOrientation(image, image, 50, (new HTuple(-50)).TupleRad() , (new HTuple(50)).TupleRad(), out HTuple Angle);
            double phi = Angle;
            HImage ImageRotate= image.RotateImage(-phi/3.14*180, "constant");
            //hswcCar.HalconWindow.ClearWindow();
            //hswcCar.HalconWindow.DispObj(ImageRotate);
            //提升对比度
            HImage ImageEmphasize = ImageRotate.Emphasize(7,7,1);

            //  //中值滤波
            //  HImage ImageMedian = ImageRotate.MedianImage("circle", 5, "mirrored");
            //  HOperatorSet.Decompose3(ImageEmphasize, out HObject r, out HObject g, out HObject b);

            //  HOperatorSet.TransFromRgb(r, g, b, out HObject h, out HObject s, out HObject v, "hsv");
            //  //自动全局阈值分割
            //  HOperatorSet.BinaryThreshold(s, out HObject Region, "max_separability", "light",
            //out HTuple UsedThreshold);
            //中值滤波
            HImage ImageMedian = ImageRotate.MedianImage("circle", 5, "mirrored");
            //转换为三通道
            HImage redImage = ImageEmphasize.Decompose3(out HImage greenImage, out HImage blueImage);
            //转换为HSV
            HImage hImage = redImage.TransFromRgb(greenImage, blueImage, out HImage sImage, out HImage vImage, "hsv");
            //自动全局阈值分割
            HRegion Region = sImage.BinaryThreshold("max_separability", "light", out HTuple UsedThreshold);
            //开运算
            HRegion RegionOpening = Region.OpeningCircle(2.0);
            //区域连通
            HRegion ConnectedRegions = RegionOpening.Connection();
            //特征提取
            HRegion SelectedRegions = ConnectedRegions.SelectShape("area", "and", 32000, 350000).SelectShape("rectangularity", "and", 0.4, 1).SelectShape("row", "and", 0, 2780);
            //膨胀
            HRegion RegionDilation1 = SelectedRegions.DilationCircle(8d);
            //填充
            HRegion RegionFillUp1 = RegionDilation1.FillUp();
            //合并
            HRegion RegionUnion1= RegionFillUp1.Union1();
            //连通
            HRegion ConnectedRegions2= RegionUnion1.Connection();
            //转化为矩形
            HRegion RegionTrans2 = ConnectedRegions2.ShapeTrans("rectangle2");
            
            
            //查数
            int Number= RegionTrans2.CountObj();
            HOperatorSet.GenEmptyObj(out HObject ROI);
            //循环判断
            for (int i = 1; i <= Number; i++)
            {
                HRegion ObjectSelected= RegionTrans2.SelectObj(i);
                double Value1 = ObjectSelected.RegionFeatures("rect2_len1");
                double Value2 = ObjectSelected.RegionFeatures("rect2_len2");
                double a = Value1 / Value2;
                if (a > 2.8&&a<4.3)
                {
                    ROI= ROI.ConcatObj(ObjectSelected);

                }
            }
            //读取ROI个数
            int Number1=ROI.CountObj();
            
            if (Number1 == 1)
            {
                //腐蚀
                HRegion ROI2=new HRegion(ROI);
                HRegion RegionErosion=ROI2.ErosionRectangle1(80,80);
                //裁剪
                HImage ImageReduced= ImageMedian.ReduceDomain(RegionErosion);
                HRegion Region1 = ImageReduced.BinaryThreshold("max_separability", "light", out int UsedThreshold1);
                //连通
                HRegion ConnectedRegions1 = Region1.Connection();
                
                //特征提取
                HRegion SelectedRegions1 = ConnectedRegions1.SelectShape("contlength", "and", 105, 150000).SelectShape("area", "and", 500, 100000);
                //膨胀
                HRegion RegionDilation = SelectedRegions1.DilationCircle(8.0);
                //合并
                HRegion RegionUnion = RegionDilation.Union1();
                //连通区域
                HRegion ConnectedRegions3 = RegionUnion.Connection();
                //交集
                HRegion RegionIntersection = ConnectedRegions3.Intersection(SelectedRegions1);
                //排序
                HRegion SortedRegions = RegionIntersection.SortRegion("character", "true", "row");
                //加载omc文件
                HOCRMlp mlp = new HOCRMlp();
                mlp.ReadOcrClassMlp("charact.omc");
                //识别信息
                HTuple Class = mlp.DoOcrMultiClassMlp(SortedRegions, ImageReduced, out HTuple Confidence);
                this.textBox1.Text = "";
                for (int i = 0; i < Class.Length; i++)
                {
                    this.textBox1.Text += Class.TupleSelect(i);
                }
                //string str = "";
                //string[] array = Class.ToSArr();
                //for (int i = 0; i < Class.Length; i++)
                //{
                //    str += array[i];
                //}
                //this.textBox1.Text = str;

                HTuple width, height;
                //获取图片的宽高
                HOperatorSet.GetImageSize(image, out width, out height);
                HOperatorSet.SetPart(hswc2.HalconWindow, 0, 0, height - 1, width - 1);
                hswc2.HalconWindow.SetColor("green");
                hswc2.HalconWindow.ClearWindow();
                hswc2.HalconWindow.DispObj(ImageReduced);
            }
            else
            {
                //筛选
                HRegion RO= new HRegion(ROI);
                HRegion ROI2 = RO.SelectShape("area", "and", 110000, 340000);
                //腐蚀
                HRegion RegionErosion = ROI2.ErosionRectangle1(80, 120);
                //裁剪
                HImage ImageReduced= ImageMedian.ReduceDomain(RegionErosion);
                //自动全局阈值分割
                HRegion Region1 = ImageReduced.BinaryThreshold("max_separability", "light", out HTuple UsedThreshold1);
                //连通
                HRegion ConnectedRegions1 = Region1.Connection();
                //筛选
                HRegion SelectedRegions1 = ConnectedRegions1.SelectShape("contlength", "and", 105, 150000).SelectShape("area", "and", 600, 100000);
                //膨胀
                HRegion RegionDilation = SelectedRegions1.DilationCircle(8d);
                //合并
                HRegion RegionUnion = RegionDilation.Union1();
                //连通
                HRegion ConnectedRegions3= RegionUnion.Connection();
                //交集
                HRegion RegionIntersection = ConnectedRegions3.Intersection(SelectedRegions1);
                //排序
                HRegion SortedRegions = RegionIntersection.SortRegion("character", "true", "row");
                //读OMC
                HOCRMlp hOCRMlp = new HOCRMlp();
                hOCRMlp.ReadOcrClassMlp("charact.omc");
                //识别
                HTuple Class = SortedRegions.DoOcrMultiClassMlp(ImageReduced, hOCRMlp, out HTuple confidence);
                this.textBox1.Text = "";
                for (int i = 0; i < Class.Length; i++)
                {
                    this.textBox1.Text += Class.TupleSelect(i);
                }

                HTuple width, height;
                //获取图片的宽高
                HOperatorSet.GetImageSize(image, out width, out height);
                HOperatorSet.SetPart(hswc2.HalconWindow, 0, 0, height - 1, width - 1);
                hswc2.HalconWindow.SetColor("green");
                hswc2.HalconWindow.ClearWindow();
                hswc2.HalconWindow.DispObj(ImageReduced);




            }

            
        }

        private void groupBox3_Enter(object sender, EventArgs e)
        {

        }
    }
}
